part of base.utils;

bool get isRelease => bool.fromEnvironment("dart.vm.product");

extension Standard<T> on T {
  T apply(Function(T e) f) {
    f(this);
    return this;
  }

  R let<R>(R Function(T e) f) {
    return f(this);
  }
}

const DEFAULT_TOAST_DURATION = Duration(seconds: 2);
const DEFAULT_TOAST_COLOR = Color(0xFF424242);

extension Utils on String {
  // md5 加密
  MD5() {
    var content = const Utf8Encoder().convert(this);
    var digest = md5.convert(content);
    return digest.toString();
  }

  void toast({
    Duration duration = DEFAULT_TOAST_DURATION,
    Color color = DEFAULT_TOAST_COLOR,
    EasyLoadingToastPosition? toastPosition,
    EasyLoadingMaskType? maskType,
    bool? dismissOnTap,
  }) {
    EasyLoading.showToast(this,
        duration: duration,
        toastPosition: toastPosition,
        maskType: maskType,
        dismissOnTap: dismissOnTap);
  }

  void error(
    String msg, {
    Duration duration = DEFAULT_TOAST_DURATION,
    Color color = DEFAULT_TOAST_COLOR,
    EasyLoadingToastPosition? toastPosition,
    EasyLoadingMaskType? maskType,
    bool? dismissOnTap,
  }) {
    EasyLoading.showError(msg,
        duration: duration, maskType: maskType, dismissOnTap: dismissOnTap);
  }

  success(
    String msg, {
    Duration duration = DEFAULT_TOAST_DURATION,
    EasyLoadingMaskType? maskType,
    bool? dismissOnTap,
  }) {
    EasyLoading.showSuccess(msg,
        duration: duration, maskType: maskType, dismissOnTap: dismissOnTap);
  }

  showInfo(
    String msg, {
    Duration duration = DEFAULT_TOAST_DURATION,
    EasyLoadingMaskType? maskType,
    bool? dismissOnTap,
  }) {
    EasyLoading.showInfo(msg,
        duration: duration, maskType: maskType, dismissOnTap: dismissOnTap);
  }

  BoxDecoration bg({BoxFit? fit, ColorFilter? colorFilter}) {
    return BoxDecoration(
      image: DecorationImage(
        fit: fit ?? BoxFit.fitWidth,
        colorFilter: colorFilter,
        image: this.assetImage(),
      ),
    );
  }

  BoxDecoration realBg({BoxFit? fit, ColorFilter? colorFilter}) {
    return BoxDecoration(
      image: DecorationImage(
        fit: fit ?? BoxFit.fitWidth,
        colorFilter: colorFilter,
        image: AssetImage(this),
      ),
    );
  }

  assetImage(
          {String host = 'assets',
          String path = 'images',
          String format = 'png',
          AssetBundle? bundle,
          ImageFrameBuilder? frameBuilder,
          ImageErrorWidgetBuilder? errorBuilder,
          String? semanticLabel,
          bool excludeFromSemantics = true,

          /// 忽略图片语义
          double? scale,
          double? width,
          double? height,
          Color? color,
          Color? dartColor,
          Animation<double>? opacity,
          BlendMode? colorBlendMode,
          BoxFit? fit,
          AlignmentGeometry alignment = Alignment.center,
          ImageRepeat repeat = ImageRepeat.noRepeat,
          Rect? centerSlice,
          bool matchTextDirection = false,
          bool gaplessPlayback = false,
          bool isAntiAlias = false,
          String? package,
          FilterQuality filterQuality = FilterQuality.low,
          int? cacheWidth,
          int? cacheHeight}) =>
      Image.asset(
        '$host/$path/$this' + '${this.indexOf('.') < 0 ? '.$format' : ''}',
        height: height,
        width: width,
        fit: fit,
        color: Get.isDarkMode ? dartColor ?? color : color,
        excludeFromSemantics: excludeFromSemantics,
        frameBuilder: frameBuilder,
        errorBuilder: errorBuilder,
        semanticLabel: semanticLabel,
        scale: scale,
        opacity: opacity,
        colorBlendMode: colorBlendMode,
        alignment: alignment,
        repeat: repeat,
        centerSlice: centerSlice,
        matchTextDirection: matchTextDirection,
        gaplessPlayback: gaplessPlayback,
        isAntiAlias: isAntiAlias,
        package: package,
        filterQuality: filterQuality,
        cacheWidth: cacheWidth,
        cacheHeight: cacheHeight,
      );

  assetRealImage(
          {String format = 'png',
          AssetBundle? bundle,
          ImageFrameBuilder? frameBuilder,
          ImageErrorWidgetBuilder? errorBuilder,
          String? semanticLabel,
          bool excludeFromSemantics = true,

          /// 忽略图片语义
          double? scale,
          double? width,
          double? height,
          Color? color,
          Color? dartColor,
          Animation<double>? opacity,
          BlendMode? colorBlendMode,
          BoxFit? fit,
          AlignmentGeometry alignment = Alignment.center,
          ImageRepeat repeat = ImageRepeat.noRepeat,
          Rect? centerSlice,
          bool matchTextDirection = false,
          bool gaplessPlayback = false,
          bool isAntiAlias = false,
          String? package,
          FilterQuality filterQuality = FilterQuality.low,
          int? cacheWidth,
          int? cacheHeight}) =>
      Image.asset(
        '$this' + '${this.indexOf('.') < 0 ? '.$format' : ''}',
        height: height,
        width: width,
        fit: fit,
        color: Get.isDarkMode ? dartColor ?? color : color,
        excludeFromSemantics: excludeFromSemantics,
        frameBuilder: frameBuilder,
        errorBuilder: errorBuilder,
        semanticLabel: semanticLabel,
        scale: scale,
        opacity: opacity,
        colorBlendMode: colorBlendMode,
        alignment: alignment,
        repeat: repeat,
        centerSlice: centerSlice,
        matchTextDirection: matchTextDirection,
        gaplessPlayback: gaplessPlayback,
        isAntiAlias: isAntiAlias,
        package: package,
        filterQuality: filterQuality,
        cacheWidth: cacheWidth,
        cacheHeight: cacheHeight,
      );

  network(
          {AssetBundle? bundle,
          ImageFrameBuilder? frameBuilder,
          ImageLoadingBuilder? loadingBuilder,
          ImageErrorWidgetBuilder? errorBuilder,
          String? semanticLabel,
          bool excludeFromSemantics = true,

          /// 忽略图片语义
          double scale = 1.0,
          double? width,
          double? height,
          Color? color,
          Color? dartColor,
          Animation<double>? opacity,
          BlendMode? colorBlendMode,
          BoxFit? fit,
          AlignmentGeometry alignment = Alignment.center,
          ImageRepeat repeat = ImageRepeat.noRepeat,
          Rect? centerSlice,
          bool matchTextDirection = false,
          bool gaplessPlayback = false,
          FilterQuality filterQuality = FilterQuality.low,
          bool isAntiAlias = false,
          Map<String, String>? headers,
          int? cacheWidth,
          int? cacheHeight}) =>
      Image.network(
        this,
        height: height,
        width: width,
        fit: fit,
        color: Get.isDarkMode ? dartColor ?? color : color,
        excludeFromSemantics: excludeFromSemantics,
        frameBuilder: frameBuilder,
        loadingBuilder: loadingBuilder,
        errorBuilder: errorBuilder,
        semanticLabel: semanticLabel,
        scale: scale,
        opacity: opacity,
        colorBlendMode: colorBlendMode,
        alignment: alignment,
        repeat: repeat,
        centerSlice: centerSlice,
        matchTextDirection: matchTextDirection,
        gaplessPlayback: gaplessPlayback,
        isAntiAlias: isAntiAlias,
        filterQuality: filterQuality,
        headers: headers,
        cacheWidth: cacheWidth,
        cacheHeight: cacheHeight,
      );
}

extension Styles on num {
  Widget get height => SizedBox(height: h.toDouble());

  /// Leaves given width of space
  Widget get width => SizedBox(width: w.toDouble());

  Widget line({indent: 10.0, endIndent: 10.0, color: KColors.c_333333}) =>
      Divider(
        height: h,
        indent: indent,
        endIndent: endIndent,
        color: color,
      );

  EdgeInsets get pl => EdgeInsets.only(top: 0, left: w, right: 0, bottom: 0);

  EdgeInsets get pr => EdgeInsets.only(top: 0, left: 0, right: w, bottom: 0);

  EdgeInsets get plr => EdgeInsets.only(top: 0, left: w, right: w, bottom: 0);

  EdgeInsets get pt => EdgeInsets.only(top: h, left: 0, right: 0, bottom: 0);

  EdgeInsets get pb => EdgeInsets.only(top: 0, left: 0, right: 0, bottom: h);

  EdgeInsets get pbl => EdgeInsets.only(top: 0, left: 0, right: 0, bottom: h);

  EdgeInsets get p => EdgeInsets.all(r.toDouble());

  toTextStyle(
      {Color? color,
      Color? dartColor,
      TextDecoration? decoration,
      double? letterSpacing,
      fontWeight = FontWeight.normal}) {
    return TextStyle(
      fontSize: sp,
      color: Get.isDarkMode ? dartColor ?? color : color,
      fontWeight: fontWeight,
      letterSpacing: letterSpacing,
      decoration: decoration,
    );
  }
}

/// Allows you to insert widgets inside a CustomScrollView
extension WidgetBox on Widget {
  Widget get toSliverBox => SliverToBoxAdapter(child: this);

  Widget onClick(Function() f) => GestureDetector(
        onTap: f,
        child: this,
      );
}

extension Http<T> on Future<Response<T>> {
  ///直接返回 数据
  Future<R?> tryAsyncOK<R, L>(R Function(L e) f,
      {bool showToast = false}) async {
    try {
      Response response = await this;
      if (response.statusCode == 200) {
        ApiResult apiResult = ApiResult.fromJson((response.data is String)
            ? jsonDecode(response.data)
            : response.data);
        if (apiResult.isSuccess()) {
          print('ok0${apiResult.data is String}');
          print(apiResult.data);
          return f(apiResult.data);
        } else {
          print(apiResult.msg);
          var exception = ApiException(response.statusCode, apiResult.msg);
          throw exception;
        }
      }
    } catch (e) {
      print(e);
      var exception = ApiException.from(e);
      if (showToast) {
        exception.message?.toast();
      }
    }
    return null;
  }

  ///直接返回 数据 不做处理
  Future<R?> tryAsyncOk1<R>({bool showToast = false}) async {
    try {
      Response response = await this;
      if (response.statusCode == 200) {
        ApiResult apiResult = ApiResult.fromJson((response.data is String)
            ? jsonDecode(response.data)
            : response.data);
        if (apiResult.isSuccess()) {
          print(apiResult.data);
          if (showToast) {
            apiResult.msg?.toast();
          }
          return apiResult.data;
        } else {
          print(apiResult.msg);
          var exception = ApiException(response.statusCode, apiResult.msg);
          throw exception;
        }
      }
    } catch (e) {
      print(e);
      var exception = ApiException.from(e);
      if (showToast) {
        exception.message?.toast();
      }
    }
    return null;
  }
}
